<template>
  <div>
    <el-card class="box-card">
      <!-- 布局响应式的布,页面的宽分成24个格 列之间的宽度 -->
      <el-row :gutter='10'>
        <el-col :span="8">
          <!-- clearable 可清空的选项 -->
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable
                    @clear='getUsers'>
            <el-button slot="append" class="el-icon-search" @click="searchUser">
            </el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="dialogFormVisibleAdd = true">添加用户
          </el-button>
        </el-col>
      </el-row>
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="index" label="序号" width="50"> </el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="status" label="状态" width="50px">
          <!-- 用插槽来获取数据 -->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" active-color="#13ce66"
                       inactive-color="#ff4949" @change='chgState(scope.row)'>
            </el-switch>
          </template>
        </el-table-column>
        <!-- width 单独设置某列的宽 -->
        <el-table-column label="操作" width="250px">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit"
                       @click="showDialogFormEdit(scope.row.id)">
            </el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete"
                       @click="delById(scope.row.id)">
            </el-button>
            <el-tooltip effect="dark" content="分配角色" placement="top"
                        :enterable='false'>
              <el-button type="warning" size="mini" icon="el-icon-setting"
                         @click="roleSet(scope.row)">
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 10,15,20,30 current-page 当前的页数,page-sizes下拉框里边的信息
      page-size 当前的查询的数据的条数 layout 控制页面的显示的信息
       -->
      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="queryInfo.pagenum"
                     :page-sizes="[1, 3, 5, 10]" :page-size="queryInfo.pagesize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加用户 -->
    <el-dialog title="添加用户" class="mydialog"
               :visible.sync="dialogFormVisibleAdd" @close='addFormClose'>
      <el-form ref="ruleFormRef" :model="addForm" :rules="rules"
               label-width="80px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleAdd = false">取 消</el-button>
        <el-button type="primary" @click="submintForm">确 定 </el-button>
      </div>
    </el-dialog>
    <!-- 修改的思路,根据id从后台查询出来数据
    根据查询出来的数据再修改,修改的数据的字段,可能很多
    页面的列表显示的不全 -->
    <el-dialog title="修改信息" class="mydialog"
               :visible.sync="dialogFormVisibleEdit">
      <el-form ref="editFormRef" :model="editForm" :rules="rules"
               label-width="80px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleEdit = false">取 消</el-button>
        <el-button type="primary" @click="submintFormEdit">确 定
        </el-button>
      </div>
    </el-dialog>
    <!-- 分配角色 -->
    <el-dialog title="分配角色" class="mydialog"
               :visible.sync="dialogRoleSetVisible">
      <el-row>
        <el-col :span="3">当前的用户:</el-col>
        <el-col :span="16">{{userInfo.username}}</el-col>
      </el-row>
      <el-row>
        <el-col :span="3">当前的角色:</el-col>
        <el-col :span="16">{{userInfo.role_name}}</el-col>
      </el-row>

      <el-select v-model="roleVal" placeholder="请选择其中一个">
        <el-option v-for="item in roleOption" :key="item.id"
                   :label="item.roleName" :value="item.id">
        </el-option>
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogRoleSetVisible = false">取 消</el-button>
        <el-button type="primary" @click="putUsersidRoleId">确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  // set 设置,add del upd desc描述
  // 中英文的混用,不许中文拼音缩写
  // 打开页面能看到数据,挂载组件的时候,就应该拿到数据了
  mounted () {
    this.getUsers();
  },
  data () {
    return {
      // 角色的id
      roleVal: '',
      roleOption: [],
      // 改动量比较少,扩展性高
      userInfo: {},
      dialogRoleSetVisible: false,
      dialogFormVisibleEdit: false,
      // 编辑的表单
      editForm: {
        username: '',
        email: '',
        mobile: ''
      },
      // 控制dialog的显隐
      dialogFormVisibleAdd: false,
      // 里边的表单
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 校验规则,:rules来绑定
      rules: {
        username: [
          { required: true, message: '必填的,可以写别的', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 5 个字符', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '必填的,可以写别的', trigger: 'blur' },
          { min: 3, max: 6, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '必填的,可以写别的', trigger: 'blur' },
          // alt + ↓
          { pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, message: '请输入正确的格式', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '必填的,可以写别的', trigger: 'blur' },
          // alt + ↓
          { pattern: /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/, message: '请输入正确的格式', trigger: 'blur' }
        ]
      },
      // 封装参数的对象
      queryInfo: {
        query: '',
        // 从哪页数据开始查
        pagenum: 1,
        // 查询的数据的条数
        pagesize: 5
      },
      // 默认是0条总数据
      total: 0,
      currentPage4: 1,
      tableData: []
    }
  },
  methods: {
    async putUsersidRoleId () {
      // 如果角色id 是空的
      if (!this.roleVal) {
        return this.$message.error("获取角色信息失败,请先选择")
      }
      console.log(this.roleVal, this.userInfo)
      const { data: { meta } } = await this.$axios.put(`users/${this.userInfo.id}/role`, { rid: this.roleVal })
      if (meta.status !== 200) {
        return this.$message.error('添加角色失败')
      }
      this.$message.success("添加角色成功")
      // 关闭dialog
      this.dialogRoleSetVisible = false
      // 清空设置的数据
      this.userInfo = {}
      this.roleVal = ''
      // 重新的渲染页面
      this.getUsers()
    },
    // 显示角色页面
    async roleSet (row) {
      this.userInfo = row;
      // 需要获取角色的列表,es6的结构
      const { data: { data, meta } } = await this.$axios.get("roles")
      if (meta.status !== 200) {
        return this.$message.error("获取角色列表失败")
      }
      this.roleOption = data
      console.log(data, meta)
      this.dialogRoleSetVisible = true;
    },
    async chgState (rowobj) {
      const uId = rowobj.id;
      // 不用去翻了,change 改后的值,会重新的赋值了
      const type = rowobj.mg_state;
      console.log(uId, type)
      const { data: { meta } } = await this.$axios.put(`users/${uId}/state/${type}`)
      if (meta.status !== 200) {
        return this.$message.error("修改状态失败")
      }
      this.$message.success("修改状态成功")
      // 重新的渲染页面
      this.getUsers()
    },
    /* 数据非常的重要,删除要谨慎,就没有删除这一项
    所有的数据,不物理删除,逻辑删除,(只是不展示了,但是数据库里边保存着)
    */
    async delById (id) {
      const back = await this.$confirm('此操作将永久删除该数据, 是否继续?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {
        return this.$message.info("取消了")
      })
      if (back !== 'confirm') {
        return this.$message.info("取消了")
      }
      const { data: { meta } } = await this.$axios.delete(`users/${id}`)
      console.log(back)
      if (meta.status !== 200) {
        return this.$message.error("删除失败")
      }
      this.$message.success("删除用户成功")
      // 重新的渲染页面
      this.getUsers()
    },
    async showDialogFormEdit (id) {
      // this.$axios.get('users/'+id)
      const { data: { data, meta } } = await this.$axios.get(`users/${id}`)
      console.log(data, meta)
      if (meta.status !== 200) {
        return this.$message.error('获取信息失败')
      }
      // 打开页面的时候就已经给好id了
      this.editForm = data
      this.dialogFormVisibleEdit = true
    },
    // 修改按钮的提交
    submintFormEdit () {
      const id = this.editForm.id;
      // 1.表单校验通过之后,才可以提交数据,validate可以校验表单的数据
      this.$refs.editFormRef.validate(async (valid) => {
        // 如果是false,表单数据有问题
        if (!valid) {
          return
        }
        // 2.数据没有问题,才往后边传数据
        // const { data: { data, meta } } = await this.$axios.put(`users/${id}`, this.editForm)
        const { data: { data, meta } } = await this.$axios.put(`users/${id}`, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        })
        // 3.判断返回的结果
        if (meta.status !== 200) {
          return this.$message.error("更新失败")
        }
        this.$message.success(meta.msg)
        // 4.重现的条用分页,刷新页面
        this.getUsers()
        console.log(data, meta)
      })
      // 5 将页面关闭
      this.dialogFormVisibleEdit = false;
    },
    // 添加按钮的提交
    submintForm () {
      // 表单校验通过之后,才可以提交数据
      this.$refs.ruleFormRef.validate(async (valid) => {
        // 如果是false,表单数据有问题
        if (!valid) {
          return
        }
        // 数据没有问题,才往后边传数据
        const { data: { data, meta } } = await this.$axios.post('users', this.addForm)
        if (meta.status !== 201) {
          return this.$message.error("添加失败")
        }
        this.$message.success(meta.msg)
        // 重现的条用分页,刷新页面
        this.getUsers()
        console.log(data, meta)
      })
      this.dialogFormVisibleAdd = false
    },
    // 关闭dialog之后,清空表单
    addFormClose () {
      // console.log('关闭了')
      this.$refs.ruleFormRef.resetFields();
    },

    async searchUser () {
      this.queryInfo.pagenum = 1;
      // es6的解构
      const { data: { data, meta } } = await this.$axios.get('users', { params: this.queryInfo })
      if (meta.status !== 200) {
        this.$message.error('获取用户信息失败')
        return
      }
      this.tableData = data.users
      this.total = data.total
      // console.log(data, meta)
    },
    async getUsers () {
      // es6的解构
      const { data: { data, meta } } = await this.$axios.get('users', { params: this.queryInfo })
      if (meta.status !== 200) {
        this.$message.error('获取用户信息失败')
        return
      }
      this.tableData = data.users
      this.total = data.total
      // console.log(data, meta)
    },
    handleSizeChange (size) {
      console.log('改变的查询的条数', size)
      this.queryInfo.pagesize = size;
      // 页面的数据重新的渲染
      this.getUsers()
    },
    handleCurrentChange (page) {
      console.log('改变的页数', page)
      this.queryInfo.pagenum = page;
      // 页面的数据重新的渲染
      this.getUsers()
    }
  }
}
</script>

<style lang="css" scoped>
/* 需要设置成全局的属性,去掉scope */
/* 让div 的宽只能容下一个字符的宽 */
/* .el-tooltip__popper {
  max-width: 10px;
  min-width: none;
} */
.mydialog {
  text-align: left;
}
</style>